package com.ruoyi.common.utils.sms;

import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.ruoyi.common.config.HuaweiSmnProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;


@Component
@Slf4j
public class HuaweiSmsSender {

    private static HuaweiSmnProperties properties;

    @Autowired
    public HuaweiSmsSender(HuaweiSmnProperties properties) {
        HuaweiSmsSender.properties = properties;
    }

//  @PostConstruct
//  public void init() {
//    ICredential auth = new BasicCredentials()
//        .withAk(properties.getAk())
//        .withSk(properties.getSk());
//
//    String regionId = properties.getRegion(); //.toUpperCase().replace("-", "_");
//    smnClient = SmnClient.newBuilder()
//        .withCredential(auth)
//        .withRegion(SmnRegion.valueOf(regionId))
//        .build();
//  }

    /**
     * 发送验证码短信
     *
     * @param phone 手机号（+86格式）
     * @param code  6位验证码
     */
    public static void sendVerificationCode(String phone, String code) {
        // Create a new request.
        Request httpClientRequest = new Request();
        try {
            // Set the request parameters.
            // AppKey, AppSecrect, Method and Url are required parameters.
            // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存放，使用时解密，确保安全；
            // 本示例以ak和sk保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
            httpClientRequest.setKey("9cc907ed24a84ca3b4a2c8b0df13b4d4");
            httpClientRequest.setSecret("3116b8c5202448da87e76698311989fb");
            httpClientRequest.setMethod("POST");
            httpClientRequest.setUrl("https://msgchinadatapat.apistore.huaweicloud.com/winnerrxd/api/v1/hw/trigger/sendMsg?DesNo=" + phone + "&Msg=【蓝吉星(北京)信息科技】您的验证码为：" + code + "，1分钟内有效，请勿泄露于他人！");
//            httpClientRequest.setBody("{\"DesNo\": \"" + phone + "\", \"Msg\": \"【蓝吉星(北京)信息科技】您的验证码为：" + "，1分钟内有效，请勿泄露于他人！\"}");
//            httpClientRequest.setBody("{}");
            httpClientRequest.addHeader("X-Winner-Platform-Hw-Access-Key", "de0d55b9432def4ad9e8ed0365494acdc0d65e764061a00653515cb9b7f327ad");
            httpClientRequest.addHeader("content-Type", "application/x-www-form-urlencoded");
        } catch (Exception e) {
            log.error(e.getMessage());
            return;
        }
        CloseableHttpClient client = null;
        try {
            // Sign the request.
            HttpRequestBase signedRequest = Client.sign(httpClientRequest, "SDK-HMAC-SHA256");
            client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClient("TLSv1.2");
            HttpResponse response = client.execute(signedRequest);
            // Print the body of the response.
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                log.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"),
                        EntityUtils.toString(resEntity, "UTF-8"));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        sendVerificationCode("17604023841", "123456");
    }

}
